package com.tchepannou.limbe.gae.dao;

import com.google.appengine.api.datastore.Key;
import com.tchepannou.limbe.model.Model;

import java.util.List;
import java.util.ListIterator;

/**
 * Implementation of {@link java.util.Iterator}
 * @param <T>
 */
class PersistentListIterator<T extends Model>
    implements ListIterator<T>
{
    //-- Attributes
    private AbstractGaeDao _dao;
    private ListIterator<Key> _it;

    //-- Constructor
    public PersistentListIterator(List<Key> keys, AbstractGaeDao dao)
    {
        _it = keys.listIterator();
        _dao = dao;
    }
    public PersistentListIterator(int index, List<Key> keys, AbstractGaeDao dao)
    {
        _it = keys.listIterator(index);
        _dao = dao;
    }

    //-- ListIterator overrides
    @Override
    public boolean hasPrevious()
    {
        return  _it.hasNext();
    }

    @Override
    public T previous()
    {
        Key key = _it.previous();
        T result = (T)_dao.findByKey(key);
        return result;
    }

    @Override
    public int nextIndex()
    {
        return _it.nextIndex();
    }

    @Override
    public int previousIndex()
    {
        return _it.nextIndex();
    }

    @Override
    public void set(T t)
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public void add(T t)
    {
        throw new UnsupportedOperationException();
    }

    //-- Iterator overrides
    public T next()
    {
        Key key = _it.next ();
        T result = (T)_dao.findByKey(key);
        return result;
    }

    public boolean hasNext()
    {
        return _it.hasNext();
    }

    public void remove()
    {
        throw new UnsupportedOperationException ();
    }
}
